package yunwo.cn.yzstation.view.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import com.zltd.decoder.Constants;

import java.util.ArrayList;
import java.util.List;

import yunwo.cn.yzstation.R;
import yunwo.cn.yzstation.adapter.PayTypeAdapter;

import yunwo.cn.yzstation.api.IcanAssigView;
import yunwo.cn.yzstation.base.BasicAdapter;

import yunwo.cn.yzstation.base.MyBaseScanActivity;
import yunwo.cn.yzstation.bean.AssigmnetBean;
import yunwo.cn.yzstation.bean.ContinueBean;
import yunwo.cn.yzstation.bean.ItemlistBean;
import yunwo.cn.yzstation.other.PickDialog;
import yunwo.cn.yzstation.other.ShowAnimationDialogUtil;
import yunwo.cn.yzstation.presenter.ScanAssigPersenter;


/**
 * Created by lao on 2017/9/9.
 */
public class ScanAssigAcivity extends MyBaseScanActivity implements View.OnClickListener,IcanAssigView{

    private ListView mScancar_lv;
    private ScanCarLvAdapter mScanCarLvAdapter;
    private LinearLayout mScanmodel;
    private TextView mModel;
    private int scanMode = Constants.SINGLE_SHOOT_MODE;
    private AssigmnetBean mAssigmentBean;
    private ContinueBean.DataBean mMContinueBean;
    private TextView mBatch;
    private TextView mCarnumber;
    private ScanAssigPersenter mScanAssigPersenter;
    private List<ItemlistBean.DataBean> mDataBeanList;

    private List<ItemlistBean.DataBean> mSelectedCollectedCars;
    private TextView mComplete;
    private List<ContinueBean.DataBean.DepartDetailListBean> mDepartDetailList
            ;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();

        if (getIntent().getSerializableExtra("AssigmentBean") != null) {
            mAssigmentBean = (AssigmnetBean) getIntent().getSerializableExtra("AssigmentBean");
            mCarnumber.setText(mAssigmentBean.getCarnumber());
            mBatch.setText(mAssigmentBean.getBatch());
        }else {
            mMContinueBean = (ContinueBean.DataBean) getIntent().getSerializableExtra("mContinue");
            mCarnumber.setText(mMContinueBean.getPlateNumber());
            mBatch.setText(mMContinueBean.getBatchNumber());
            conversionBean(mMContinueBean);
            mScanCarLvAdapter = new ScanCarLvAdapter(ScanAssigAcivity.this);
            mScanCarLvAdapter.refreshDataAndNotifyDataSetChanged(mSelectedCollectedCars);
            mScancar_lv.setAdapter(mScanCarLvAdapter);
        }
    }



    private void initView() {
        mSelectedCollectedCars = new ArrayList<>();
        mComplete = (TextView) findViewById(R.id.complete);
        mModel = (TextView) findViewById(R.id.model);
        mScancar_lv = (ListView) findViewById(R.id.scancar_lv);
        mScanmodel = (LinearLayout) findViewById(R.id.scanmodel);
        mBatch = (TextView) findViewById(R.id.batch);
        mCarnumber = (TextView) findViewById(R.id.carnumber);
        mComplete.setOnClickListener(this);
        mScanmodel.setOnClickListener(this);
        mScanAssigPersenter = new ScanAssigPersenter(this, this);
        mScanAssigPersenter.getoBtainTrack();
    }

    @Override
    protected String settiltile() {
        return "扫码装车";
    }

    @Override
    protected int getLayoutRsid() {
        return R.layout.activity_scancar;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.scanmodel:
                PickDialog selectPayTypeDialog2 = ShowAnimationDialogUtil.showDialog(
                        ScanAssigAcivity.this, R.layout.activity_pay_type_dialog);
                List<String> list = new ArrayList<>();
                list.add("按单扫码"); list.add("按件扫码");
                initPayTypeDialogView(selectPayTypeDialog2, list, mModel);
                break;
            case R.id.complete:
                if (mSelectedCollectedCars.size()==0) {
                    Toast.makeText(ScanAssigAcivity.this,"请扫描数据",Toast.LENGTH_SHORT).show();
                    return;
                }
                mScanAssigPersenter.complete(mAssigmentBean,mMContinueBean,mSelectedCollectedCars);
                break;
        }
    }
    private void initPayTypeDialogView(final PickDialog selectPayTypeDialog, final List<String> codeName,
                                       TextView paymentTV) {
        View view = selectPayTypeDialog.getView();
        ListView myListview = (ListView) view.findViewById(R.id.myListview);
        PayTypeAdapter payTypeAdapter = new PayTypeAdapter(ScanAssigAcivity.this, codeName, selectPayTypeDialog, paymentTV, false);
        myListview.setAdapter(payTypeAdapter);
        TextView cancelTV = (TextView) view.findViewById(R.id.cancelTV);
        cancelTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectPayTypeDialog.dismiss();
            }
        });
    }



    //pda
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        try {
            /**
             * 如果在按下扫描键的时候,当前scanmode=2[按键保持模式],必须mDecoderMgr.
             * dispatchScanKeyEvent(event); 对应的,在onKeyUp中也要同样的做法.
             */
            if (mDecoderMgr.getScanMode() == 2 && keyCode == 96
                    && event.getRepeatCount() == 0) {

                mDecoderMgr.dispatchScanKeyEvent(event);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 参考onKeyDown的实现
     */
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (mDecoderMgr.getScanMode() == 2 && keyCode == 96
                && event.getRepeatCount() == 0) {
          /*  mSingleBtn.setTextColor(Color.BLACK);
            mContinueBtn.setTextColor(Color.BLACK);*/
            mDecoderMgr.dispatchScanKeyEvent(event);
        }
        return super.onKeyUp(keyCode, event);
    }
    final List<String> list = new ArrayList<>();


    @Override
    public void onDecoderStatusChanage(final int arg0) {
        super.onDecoderStatusChanage(arg0);

    }

    //pda 扫描回调接口
    @Override
    public void onDecoderResultChanage(final String result, final String time) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                Toast.makeText(ScanAssigAcivity.this, result, Toast.LENGTH_SHORT).show();

                switch (mModel.getText().toString()) {
                    case "按件扫码":
                        boolean flag = false;
                        for (int i = 0; i < mDataBeanList.size(); i++) {
                            if (result.equals(mDataBeanList.get(i).getSubTrackingNumber())) {
                                if (!mSelectedCollectedCars.contains(mDataBeanList.get(i))) {
                                    mSelectedCollectedCars.add(mDataBeanList.get(i));
                                    //适配器刷新
                                    mScanCarLvAdapter = new ScanCarLvAdapter(ScanAssigAcivity.this);
                                    mScanCarLvAdapter.refreshDataAndNotifyDataSetChanged(mSelectedCollectedCars);
                                    mScancar_lv.setAdapter(mScanCarLvAdapter);
                                    flag = true;
                                    break;
                                }else {
                                    Toast.makeText(ScanAssigAcivity.this,"自运单"+result+"已装车!",Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                        if (!flag){
                            Toast.makeText(ScanAssigAcivity.this,"不能添加此运单",Toast.LENGTH_SHORT).show();
                        }

                        break;

                    case "按单扫码":
                        String waybill = "";
                        if (result.contains("-")) {
                            String[] split = result.split("-");
                            waybill = split[0];
                        }else {
                            String[] split = result.split("_");
                            waybill = split[0];
                        }

                        boolean flag1 = false;
                        for (int i = 0; i < mDataBeanList.size(); i++) {
                            if (waybill.equals(mDataBeanList.get(i).getTrackingNumber())) {
                                if (!mSelectedCollectedCars.contains(mDataBeanList.get(i))) {
                                    mSelectedCollectedCars.add(mDataBeanList.get(i));
                                    mScanCarLvAdapter = new ScanCarLvAdapter(ScanAssigAcivity.this);
                                    mScanCarLvAdapter.refreshDataAndNotifyDataSetChanged(mSelectedCollectedCars);
                                    mScancar_lv.setAdapter(mScanCarLvAdapter);
                                }else {
                                    Toast.makeText(ScanAssigAcivity.this,"自运单"+result+"已装车!",Toast.LENGTH_SHORT).show();
                                }
                            }
                        }


                        break;

                }


            }
        });



      /*  boolean flag = false;

        for (int i = 0; i < mItemBeans.size(); i++) {

            String childTrackingNumAli = mItemBeans.get(i).getChildTrackingNumAli();
            if (result.equals(mItemBeans.get(i).getChildTrackingNumAli())) {
                if (!infoList.contains(mItemBeans.get(i))) {
                    infoList.add(mItemBeans.get(i));
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                        }
                    });
                    flag = true;
                    break;
                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(ForShipScannerActivity.this,"自运单"+result+"已装车!",Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }
        if (!flag){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(ForShipScannerActivity.this,"不能添加此运单",Toast.LENGTH_SHORT).show();
                }
            });
        }
*/



/*        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(ForShipActivity.this, result, Toast.LENGTH_SHORT).show();
                for (int i = 0; i < mItemBeans.size(); i++) {
                    String childTrackingNumAli = mItemBeans.get(i).getChildTrackingNumAli();
                    list.add(childTrackingNumAli);
                }
                Log.d("xxxxxx", list.toString());

            }
        });*/


    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BUTTON_A
                && event.getAction() == KeyEvent.ACTION_DOWN
                && event.getRepeatCount() == 0) {
            if (scanMode == 0) {
//				singleShootOnClick(null);
//                test2();
                mDecoderMgr.setScanMode(0);
                mDecoderMgr.singleShoot();
                return true;
            } else if (scanMode == 1) {
//                continuousShootOnClick(null);
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }


    @Override
    public void getoBtainTrackSueecss(List<ItemlistBean.DataBean> dataBeanList) {
        mDataBeanList = dataBeanList;
       /* mScanCarLvAdapter = new ScanCarLvAdapter(ScanAssigAcivity.this);
        mScanCarLvAdapter.refreshDataAndNotifyDataSetChanged(dataBeanList);
        mScancar_lv.setAdapter(mScanCarLvAdapter);*/
    }

    @Override
    public void completeSueescc() {
        Intent intent = new Intent(ScanAssigAcivity.this, AssembleActivity.class);
        startActivity(intent);
        finish();
    }
    private void conversionBean(ContinueBean.DataBean mContinueBean) {
        mDepartDetailList = mContinueBean.getDepartDetailList();
        for (int i = 0; i < mDepartDetailList.size(); i++) {
            ItemlistBean.DataBean dataBean = new ItemlistBean.DataBean();
            dataBean.setBeginOrganName(mDepartDetailList.get(i).getBeginOrganName());
            dataBean.setTrackingNumber(mDepartDetailList.get(i).getTrackingNumber());
            dataBean.setSubTrackingNumber(mDepartDetailList.get(i).getSubTrackingNumber());
            dataBean.setGoodsNumber(mDepartDetailList.get(i).getGoodsNumber());
            dataBean.setEndOrganName(mDepartDetailList.get(i).getEndOrganName());
            dataBean.setBeginOrganId(mDepartDetailList.get(i).getEndOrganId());
            dataBean.setWeight(mDepartDetailList.get(i).getWeight());
            dataBean.setFreight(mDepartDetailList.get(i).getFreight());
            dataBean.setEndOrganId(mDepartDetailList.get(i).getEndOrganId());
            dataBean.setVolume(mDepartDetailList.get(i).getVolume());
            dataBean.setConsigneeAddress(mDepartDetailList.get(i).getConsigneeName());

            mSelectedCollectedCars.add(dataBean);

        }
    }
    class ScanCarLvAdapter extends BasicAdapter<ItemlistBean.DataBean> {
        public ScanCarLvAdapter(Context mctx) {
            super(mctx);
        }

        @Override
        protected int setItemLayout() {
            return R.layout.item_scancar;
        }

        @Override
        protected void bindData(View convertView, ItemlistBean.DataBean data, final int position) {
            ImageView Remove = get(convertView, R.id.Remove);
            TextView waybillTV = get(convertView, R.id.waybillTV);
            TextView goodsNameTV = get(convertView, R.id.goodsNameTV);
            TextView destinationTV = get(convertView, R.id.destinationTV);
            waybillTV.setText(data.getSubTrackingNumber());
            goodsNameTV.setText(data.getConsigneeName());
            destinationTV.setText(data.getEndOrganName());
            Remove.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mSelectedCollectedCars.remove(position);
                    notifyDataSetChanged();
                    mScanCarLvAdapter = new ScanCarLvAdapter(ScanAssigAcivity.this);
                    mScanCarLvAdapter.refreshDataAndNotifyDataSetChanged(mSelectedCollectedCars);
                    mScancar_lv.setAdapter(mScanCarLvAdapter);
                }
            });
        }
    }

}
